<?php
/**
 * ShopEx licence
 *
 * @copyright  Copyright (c) 2005-2010 ShopEx Technologies Inc. (http://www.shopex.cn)
 * @license  http://ecos.shopex.cn/ ShopEx License
 */

class b2c_ctl_site_gallery extends b2c_frontpage{

    var $_call = 'index';
    var $type='goodsCat';
    var $seoTag=array('shopname','goods_amount','goods_cat','goods_cat_p','goods_type','brand','sort_path');

    public function __construct(&$app) {
        parent::__construct($app);
        $shopname = $app->getConf('system.shopname');
        if(isset($shopname)){
            $this->title = app::get('b2c')->_('商品分类_').$shopname;
            $this->keywords = app::get('b2c')->_('商品分类_').$shopname;
            $this->description = app::get('b2c')->_('商品分类_').$shopname;
        }
		$this->pagedata['request_url'] = $this->gen_url( array('app'=>'b2c','ctl'=>'site_product','act'=>'get_goods_spec') );
    }

    public function index($cat_id='',$urlFilter=null,$orderBy=0,$tab=null,$page=1,$cat_type=null,$view=null) {

        $urlFilter=htmlspecialchars(urldecode($urlFilter));
        if($_GET['scontent'])
            $urlFilter = $_GET['scontent'];
        if($cat_id == '_ANY_'){
            unset($cat_id);
        }
        if($cat_id){
            $cat_id=explode(",",$cat_id);
            foreach($cat_id as $k=>$v){
                if($v) $cat_id[$k]=intval($v);
            }
            $this->id = implode(",",$cat_id);
        }
        if( !$cat_id  ){
            $cat_id = array('');
            $this->id = '';
        }
        $pageLimit = $this->app->getConf('gallery.display.listnum');
        $pageLimit = ($pageLimit ? $pageLimit : 20);
        $this->pagedata['pdtPic']=array('width'=>100,'heigth'=>100);
        $productCat = &$this->app->model('goods_cat');
        $virCatObj = &$this->app->model('goods_virtual_cat');
        if($cat_type){
            $GLOBALS['runtime']['path'] = $virCatObj->getPath($cat_type,'');
        }else{
            $GLOBALS['runtime']['path'] = $productCat->getPath($cat_id[0],'');
        }

        $this->pagedata['childnode'] = $productCat->getCatParentById($cat_id,'index');

        $objGoods = $this->app->model('goods');
        if(empty($view))
            $view = $this->app->getConf('gallery.default_view')?$this->app->getConf('gallery.default_view'):'index';
        $goods_cat = &$this->app->model('goods_cat');
        if( $cat_id ){
            $type_filter = $goods_cat->dump(array('cat_id'=>$cat_id),'type_id');
        }
        $cat = kernel::service('b2c_site_goods_list_viewer_apps')->get_view($cat_id,$view,$type_filter['type_id']);
        $args = array($this->id,urlencode($urlFilter),$orderBy,$tab,$page,$cat_type,$view);
        $this->pagedata['args'] = $args;
        $this->pagedata['args1'] = $args[1];
        $args[1] = null;
        $this->pagedata['args2'] = $args;


        if($this->app->getConf('system.seo.noindex_catalog'))
            $this->header .= '<meta name="robots" content="noindex,noarchive,follow" />';

        $searchtools = &$this->app->model('search');
        $path =array();

        $propargs = $searchtools->decode($urlFilter,$path,$cat);

        if(is_array($propargs)){
	        foreach($propargs as $rk=>$rv){
	        	$pos = strpos($rk,'p_');
	            if($pos === 0){
	            	$propz[$rk] = $rv[0];
	                $rk =substr($rk,2);
	                $proparg[$rk] = $rv;
	                $prot[] = $rk;
	            }
	        }
        }

       $this->pagedata['prot'] = $prot;
       $filter = $propargs;
       if(is_array($filter)){
            $filter=array_merge(array('cat_id'=>$cat_id,'marketable'=>'true'),$filter);
            if( ($filter['cat_id'][0] === '' || $filter['cat_id'][0] === null ) && !isset( $filter['cat_id'][1] ) )
                unset($filter['cat_id']);
            if( ($filter['tag'][0] === '' || $filter['tag'][0] === null ) && !isset( $filter['tag'][1] ) )
                unset($filter['tag']);
            if( ($filter['brand_id'][0] ==='' || $filter['brand_id'][0] === null) && !isset( $filter['brand_id'][1] ))
                unset($filter['brand_id']);
        }else{
            $filter = array('cat_id'=>$cat_id,'marketable'=>'true');
        }
        //--------获取类型关联的规格
        $type_id = $type_filter['type_id'];

        $gType = &$this->app->model('goods_type');
        $SpecList = $gType->getSpec($type_id,1);//获取关联的规格

        $oGoodsTypeSpec = $this->app->model('goods_type_spec');
        $type_spec = $oGoodsTypeSpec->get_type_spec($type_id);

        $oSpecification = &$this->app->model('specification');
        $filter['cat_id'] = $cat_id;
        $filter['goods_type'] = 'normal';
        $filter['marketable'] = 'true';
        //-----查找当前类别子类别的关联类型ID
        if ($urlFilter){
            if($vcat['type_id']){
                //$filter['type_id']=$vcat['type_id'];
                $filter['type_id']=null;

            }
        }
        //--------

       foreach($path as $p){
            $arg = unserialize(serialize($this->pagedata['args']));
            $arg[1] = $p['str'];
            $title = array();
            if($p['type']=='brand_id'){
                $brand = array();

                foreach($cat['brand'] as $b){
                    $brand[$b['brand_id']] = $b['brand_name'];
                }
                foreach($p['data'] as $i){
                    $title[] = $brand[$i];
                    $tip = __("品牌");
                }
                unset($brand);
            }elseif(substr($p['type'],0,2)=='s_'){
                $spec = array();
                foreach($p['data'] as $spk => $spv){
                    $tmp=explode(",",$spv);
                    $tip = $SpecList[$tmp[0]]['name'];
                    $title[]=$SpecList[$tmp[0]]['spec_value'][$tmp[1]]['spec_value'];
                    $g['pdt_desc']=$SpecList[$tmp[0]]['spec_value'][$tmp[1]]['spec_value'];/*前台搜索商品规格筛选，所要获取的pdt_desc*/

                }
            }
            $curSpec[$tmp[0]]=$tmp[1];
        }
        $this->pagedata['tabs'] = $cat['tabs'];
        $this->pagedata['cat_id'] = implode(",",$cat_id);
        $views = $cat['setting']['list_tpl'];

        foreach($views as $key=>$val){
            $this->pagedata['views'][$key] = array($this->id,'',$orderBy,$tab,$page,$cat_type,$val);

        }


        if($cat['tabs'][$tab]){
            parse_str($cat['tabs'][$tab]['filter'],$_filter);
            $filter = array_merge($filter,$_filter);
        }
        if(isset($this->pagedata['orderBy'][$orderBy])){
            $orderby = $this->pagedata['orderBy'][$orderBy]['sql'];
        }

        $selector = array();
        $search = array();

       /***********************/

        if ($SpecList){
            if ($curSpec)
                $curSpecKey=array_keys($curSpec);
            foreach($SpecList as $spk => $spv){
                $selected=0;
                if ($curSpecKey&&in_array($spk,$curSpecKey)){
                    $spv['spec_value'][$curSpec[$spk]]['selected']=true;
                    $selected=1;
                }
                if ($spv['spec_style']=="select"){ //下拉
                    $SpecSelList[$spk] = $spv;
                    if ($selected)
                        $SpecSelList[$spk]['selected'] = true;
                }
                elseif ($spv['spec_style']=="flat"){
                    $SpecFlatList[$spk] = $spv;
                    if ($selected)
                        $SpecFlatList[$spk]['selected'] = true;
                }
            }
        }


        $this->pagedata['filter'] = $this->filter;
        $this->pagedata['SpecFlatList'] = $SpecFlatList;
        $this->pagedata['specimagewidth'] = $this->app->getConf('spec.image.width');
        $this->pagedata['specimageheight'] = $this->app->getConf('spec.image.height');
        /************************/

        if (is_array($cat['brand'])){
            foreach($cat['brand'] as $bk => $bv){
                $bCount=0;
                if(is_array($filter['brand_id']))
                    $bid = array_flip($filter['brand_id']);
                $brand = array('name'=>app::get('b2c')->_('品牌'),'value'=>$bid);
                if(is_array($bv)){
                	$bfilter['brand_id'] = $bv['brand_id'];
	                $bfilter = array_merge($bfilter,$filter);
	                $bCount = $objGoods->count($bfilter);
                }
                if ($bCount>0){
                    $tmpOp[$bv['brand_id']]=$bv['brand_name']."<span class='num'>(".$bCount.")</span>";
                }

            }

            $brand['options'] = $tmpOp;
            $selector['brand_id'] = $brand;


        }

        foreach((array)$cat['props'] as $prop_id=>$prop){

            if($prop['type']=='select'){
                $prop['value'] = $filter['p_'.$prop_id][0];
                $searchSelect[$prop_id] = $prop;
            }elseif($prop['search']=='input'){
                $prop['value'] = ($filter['p_'.$prop_id][0]);
                $searchInput[$prop_id] = $prop;
            }elseif($prop['search']=='nav'){

                if(is_array($filter['brand_id'])&&isset($filter['p_'.$prop_id]))
                    $prop['value'] = array_flip($filter['p_'.$prop_id]);
                $plugadd=array();

                foreach($goods_relate as $k=>$v){

                    if($v["p_".$prop_id]!=null){

                        if($plugadd[$v["p_".$prop_id]]){
                            $plugadd[$v["p_".$prop_id]]=$plugadd[$v["p_".$prop_id]]+1;
                        }else{
                            $plugadd[$v["p_".$prop_id]]=1;
                        }
                    }
                    $aFilter['goods_id'][] = $v['goods_id'];    //当前的商品结果集
                }
                $navselector=0;

                foreach($prop['options'] as $q=>$e){
                    if($plugadd[$q]){
                        $prop['options'][$q]=$prop['options'][$q]."<span class='num'>(".$plugadd[$q].")</span>";
                        if (!$navselector)
                            $navselector=1;
                    }else{
                        unset($prop['options'][$q]);
                    }
                }
                $selector[$prop_id] = $prop;
            }
        }

        if ($navselector){
            $nsvcount=0;
            $noshow=0;
            foreach($selector as $sk => $sv){
                if ($sv['value']){
                    $nsvcount++;
                }
                if (is_numeric($sk)&&!$sv['show']){
                    $noshow++;
                }
            }
            if ($nsvcount==intval(count($selector)-$noshow))
                $navselector=0;
        }
        foreach((array)$cat['spec'] as $spec_id=>$spec_name){
            $sId['spec_id'][] = $spec_id;
        }

        $cat['ordernum'] = $cat['ordernum']?$cat['ordernum']:array(''=>2);
        if ($cat['ordernum']){
            if ($selector){
                foreach($selector as $key => $val){
                    if(!in_array($key,$cat['ordernum'])&&$val){
                        $selectorExd[$key]=$val;
                    }
                }
            }
        }


        $this->pagedata['orderBy'] = $objGoods->orderBy();//排序方式
        if(!isset($this->pagedata['orderBy'][$orderBy])){
            $this->_response->set_http_response_code(404);
        }else{
            $orderby = $this->pagedata['orderBy'][$orderBy]['sql'];
        }

        $selector['ordernum'] = $cat['ordernum'];
        if(app::get('base')->getConf('server.search_server.search_goods')){
           $searchApp = search_core::instance('search_goods');
           $sfilter = $filter;
           $sfilter['from'] = $pageLimit*($page-1);     //分页
	       $sfilter['to'] = $pageLimit;
	       $sfilter['order'] = $orderby;
	       $sfilter['scount'] = count($searchSelect);
        }
        if(is_object($searchApp)){
	       $squery = $searchApp->query($sfilter);
           $res = $searchApp->commit();
           $nprop = $squery;
	       if($squery === false){
               $aProduct = $objGoods->getList('*',$filter,$pageLimit*($page-1),$pageLimit,$orderby);
               $count = $objGoods->count($filter);
	       }else{
	           $rfilter['goods_id'] = $res['result'];
               $count = $res['total'];
               $search_data = $objGoods->getList('*',$rfilter);
               if(is_array($res['result'])){
                   foreach($res['result'] as $v){
                       foreach($search_data as $val){
                           if($v == $val['goods_id']){
                               $aProduct[] = $val;
                           }
                       }
                   }
               }
	       }
        }else{
            $aProduct = $objGoods->getList('*',$filter,$pageLimit*($page-1),$pageLimit,$orderby);
            $count = $objGoods->count($filter);
        }

        if(is_object(kernel::service('propselect.prop_search')))
            $dprop = kernel::service('propselect.prop_search')->getProps($filter,$propz,$prot,$dprop,$searchSelect);

		$this->pagedata['dprop'] = $dprop;
		$this->pagedata['nprop'] = $nprop;

        //对商品进行预处理
        $this->pagedata['mask_webslice'] = $this->app->getConf('system.ui.webslice')?' hslice':null;
        $this->pagedata['searchInput'] = &$searchInput;
        $this->pagedata['selectorExd'] = $selectorExd;
        $this->cat_id = $cat_id;
        $this->_plugins['function']['selector'] = array(&$this,'_selector');
        $this->pagedata['pager'] = array(
            'current'=>$page,
            'total'=>ceil($count/$pageLimit),
            'link'=>  $this->gen_url(array('app'=>'b2c', 'ctl'=>'site_gallery','full'=>1,'act'=>'index','args'=>array(implode(',',$cat_id),'',$orderBy,$tab,($tmp=time()),'',$view))).'?scontent='.urlencode($p['str']),
            'token'=>$tmp);
        if($page != 1 && $page > $this->pagedata['pager']['total']){
            $this->_response->set_http_response_code(404);
        }
        if(!$count){
            $this->pagedata['emtpy_info'] = kernel::single('site_errorpage_get')->getConf('errorpage.search');

        }
        $this->pagedata['searchtotal']=$count;
        if(is_array($aProduct) && count($aProduct) > 0){
            $objProduct = $this->app->model('products');
            if($this->app->getConf('site.show_mark_price')=='true'){
                $setting['mktprice'] = $this->app->getConf('site.show_mark_price');
                if(isset($aProduct)){
                    foreach($aProduct as $pk=>$pv){
                        if(empty($aProduct[$pk]['mktprice']))
                        $aProduct[$pk]['mktprice'] = $objProduct->getRealMkt($pv['price']);
                    }
                }
            }else{
                $setting['mktprice'] = 0;
            }
            $setting['saveprice'] = $this->app->getConf('site.save_price');
            $setting['buytarget'] = $this->app->getConf('site.buy.target');
            $this->pagedata['setting'] = $setting;
            //spec_desc
            $siteMember = $this->get_current_member();
            $this->site_member_lv_id = $siteMember['member_lv'];
            $oGoodsLv = &$this->app->model('goods_lv_price');
            $oMlv = &$this->app->model('member_lv');
            $mlv = $oMlv->db_dump( $this->site_member_lv_id,'dis_count' );

            $rfilter['marketable'] = 'true';
            $pro = $objProduct->getList('product_id, spec_info, price, freez, store,marketable, goods_id', $rfilter);
            unset($rfilter['marketable']);
            $rfilter['level_id'] = $this->site_member_lv_id;
            $glv = $oGoodsLv->getList('goods_id,product_id,price', $rfilter);

    	    $tmpGoods = array();
            foreach ($aProduct as $key=>&$val) {

             	if( $this->site_member_lv_id ){
	                foreach( $pro as &$tv ){
	                    foreach($glv as $k1 => $v1){
            		        if($val['goods_id'] == $v1['goods_id']){
	            		        $tmpGoods[$v1['product_id']] = $v1['price'];
	                                 $tv['price'] = (isset( $tmpGoods[$v1['product_id']] )?$tmpGoods[$v1['product_id']]:( $mlv['dis_count']*$v1['price'] ));
	                                 $spec_desc_info[] = $tv;
	            		    }
	            		    $val['price'] = $tv['price'];
            			}
            		}
                }

                /*
            	foreach($glv as $k1 => $v1){
            		if($val['goods_id'] === $v1['goods_id']){
            			if( $this->site_member_lv_id ){
	            		    $tmpGoods[$v1['product_id']] = $v1['price'];
	            		    foreach( $pro as &$tv ){
	            		    	if($val['goods_id'] === $tv['goods_id']){
	                                 $tv['price'] = (isset( $tmpGoods[$tv['product_id']] )?$tmpGoods[$tv['product_id']]:( $mlv['dis_count']*$tv['price'] ));
	                                 $spec_desc_info[] = $tv;
	            		    	}
	            		    }
	            		    $val['price'] = $tv['price'];
            			}
            		}
                }
                 */
            	foreach($pro as $tk=>&$tv){
            		if($val['goods_id'] === $tv['goods_id']){
                        if( $tv['price'] < $val['price'] )
                            $val['price'] = $tv['price'];
                       $spec_desc_info[] = $tv;
            		}
            	}
                $val['spec_desc_info'] = $spec_desc_info;
                $aProduct[$key]['product_id'] = $pro[0]['product_id'];
                unset($spec_desc_info);
            }
            // add here by liuyong
            // show tag on goods image
            foreach( kernel::servicelist('tags_special.add') as $services ) {
                if ( is_object($services)) {
                    if ( method_exists( $services, 'add') ) {
                        $services->add( $rfilter['goods_id'], $aProduct );
                    }
                }
            }
            // end of add
            $this->pagedata['products'] = &$aProduct;
        }

        $aData = $this->get_current_member();
        if(!$aData['member_id']){
            $this->pagedata['login'] = 'nologin';
        }
        if($SpecSelList){
            $this->pagedata['SpecSelList'] = $SpecSelList;
        }
        if($searchSelect){
            $this->pagedata['searchSelect'] = &$searchSelect;
        }
        $this->pagedata['curView'] = $view;
        $this->pagedata['selector'] = &$selector;
        $this->pagedata['cat_type'] = $cat_type;
        if($GLOBALS['search_array']&&is_array($GLOBALS['search_array'])){
            $this->pagedata['search_array'] = implode("+",$GLOBALS['search_array']);
        }
        $this->pagedata['_PDT_LST_TPL'] = $cat['tpl'];
        $this->pagedata['filter'] = $filter;
        $this->set_tmpl('gallery');
        $this->pagedata['gallery_display'] = $this->app->getConf('gallery.display.grid.colnum');
        $this->pagedata['property_select'] = $this->app->getConf('site.property.select');
        $imageDefault = app::get('image')->getConf('image.set');
        $this->pagedata['image_set'] = $imageDefault;
        $this->pagedata['defaultImage'] = $imageDefault['S']['default_image'];
        $this->pagedata['proparg'] = $proparg;

        $this->page('site/gallery/index.html');
    }
}
